package org.example.gobang.api;

import org.example.gobang.model.User;
import org.example.gobang.model.UserMapper;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@RestController
public class UserAPI {

    @Resource
    private UserMapper userMapper;
    @RequestMapping(value = "/login",method = RequestMethod.POST)
    public Object login(String username, String password, HttpServletRequest request) {
        // 关键操作 根据username去数据库中查找数据
        // 如果找到username匹配的,并且密码也匹配的,则登录成功
        User user = userMapper.selectByName(username);
        System.out.println("[login] username = " + username);
        if(user == null || !user.getPassword().equals(password)) {
            System.out.println("登录失败");
            return new User();
        }
        HttpSession session = request.getSession(true);
        session.setAttribute("user", user);
        return user;
    }

    @RequestMapping(value = "/register",method = RequestMethod.POST)
    public Object register(String username, String password) {
        try {
            User user = new User();
            user.setUsername(username);
            user.setPassword(password);
            userMapper.insert(user);
            return user;
        }catch (org.springframework.dao.DuplicateKeyException e) {
            return new User();
        }
    }

    @RequestMapping(value = "/userInfo",method = RequestMethod.GET)
    public Object getUserInfo(HttpServletRequest req) {
        try {
            HttpSession httpSession = req.getSession(false);
            User user = (User) httpSession.getAttribute("user");
            //return user (这里原先返回的是登录之后的user，并不是对战之后更新的user)
            // 拿着这个 user 对象, 去数据库中找, 找到最新的数据
            User newUser = userMapper.selectByName(user.getUsername());
            return newUser;
        }catch (NullPointerException e) {
            return new User();
        }

    }
}
